/**
 * @description 发布作品
 */

const _ = require('lodash')
const { updateWork, findOneWork, updatePublishContent } = require('../../service/works')
const { ErrorRes, SuccessRes } = require('../../res-model/index')
const {
  publishWorkFailInfo,
  publishWorkDbErrorFailInfo,
  forceOffLineFailInfo
} = require('../../res-model/failInfo/index')
const { h5Origin } = require('../../config/index')
const { publishWorkClearCache } = require('../../cache/works/publish')

/**
 * 获取所有图片
 * @param {object}} work 作品信息
 */
function getWorkImgs(work = {}) {
  const { content = {} } = work
  const { components = [], props = {}, setting = {} } = content
  const { backgroundImage = '' } = props // 背景图片
  const { shareImg = '' } = setting // 分享小图标

  // 存储结果
  const imgs = []

  if (backgroundImage) imgs.push(backgroundImage)
  if (shareImg) imgs.push(shareImg)

  // 遍历所有组件
  components.forEach((component = {}) => {
    // component 结构参考 https://github.com/imooc-lego/lego-components
    const { name, props = {} } = component // eslint-disable-line
    if (name !== 'l-image') return // 不是图片组件
    const { imageSrc } = props
    if (imageSrc) imgs.push(imageSrc)
  })

  return imgs
}

/**
 * 发布项目
 * @param {string} id workId
 * @param {string} author 作者 username
 * @param {boolean} isTemplate 设置为模板
 */
async function publishWork(id, author, isTemplate = false) {
  const work = await findOneWork({ id, author })
  if (!work) {
    return new ErrorRes(publishWorkFailInfo, 'id 或者作者不匹配')
  }

  // 是否强制下线
  if (parseInt(work.status, 10) === 3) {
    return new ErrorRes(forceOffLineFailInfo)
  }

  const updateData = {
    status: 2,
    latestPublishAt: new Date(),
    ...(isTemplate && { isTemplate: true })
  }

  try {
    const publishContentId = await updatePublishContent(work.content, work.publishContentId)
    const result = await updateWork(
      {
        ...updateData,
        publishContentId
      },
      { id, author }
    )
    if (!result) {
      return new ErrorRes(publishWorkFailInfo)
    }
  } catch (ex) {
    console.error('发布作品错误', id, ex)
    // TODO 报警。title 中要有作品 id `发布作品 ${id} 错误` ，报警会根据 title 缓存
    return new ErrorRes(publishWorkDbErrorFailInfo)
  }

  // 重新发布，清空 h5-server 缓存
  publishWorkClearCache(id)

  // 发布成功，返回连接 url: base/p/:id-uuid   id-uuid 保证唯一
  const url = `${h5Origin}/p/${work.id}-${work.uuid}`
  return new SuccessRes({ url })
}

module.exports = {
  publishWork
}
